package com.coollang.smartbra.utils;

import android.os.Handler;
import android.os.Message;

/**
 * 时间监听
 */

public class RunTimeUtils {

    public long timer = 0; // 跑步的时间
    public long startTimer = 0;// 开始时间
    public Thread thread; // 控制时间的子线程
    private static RunTimeUtils instance;// 创建单例
    private RunTimeListener mTimeListener;// 设置时间的监听器

    private RunTimeUtils() {
    }

    public static RunTimeUtils getInstance() {
        if (instance == null) {
            instance = new RunTimeUtils();
        }
        return instance;
    }

    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // 在UI中设置时间
            if (mTimeListener != null) {
                mTimeListener.onRunTimeChange(timer / 1000);
            }
        }
    };

    public void initTime() {
        if (thread == null) {
            startTimer = System.currentTimeMillis();
            thread = new Thread() {
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        if (!isPause) {
                            if (startTimer != System.currentTimeMillis()) {
                                timer = System.currentTimeMillis() - startTimer;
                            }
                            Message msg = new Message();
                            handler.sendMessage(msg);// 通知主线程
                        }
                    }
                }
            };
            thread.start();
        }
    }

    private boolean isPause = false;
    private long pauseTime = 0;

    public void setPause(boolean pause) {

        if (isPause == pause) {
            return;
        }

        if (pause) {
            // 暂停
            // 记录当前时间
            pauseTime = System.currentTimeMillis();
        } else {
            if (pauseTime == 0) {
                return;
            }
            // 取消暂停
            // 记录当前时间 同时startTime 加上
            pauseTime = System.currentTimeMillis() - pauseTime;
            startTimer += pauseTime;
            pauseTime = 0;
        }

        isPause = pause;
    }

    public interface RunTimeListener {
        void onRunTimeChange(long timer);
    }

    public void setTimeListener(RunTimeListener mTimeListener) {
        this.mTimeListener = mTimeListener;
    }

    private long stopTime;

    public long getStopTime() {
        return stopTime;
    }

    // 结束
    public void stopTimer() {
        handler.removeCallbacks(thread);
        mTimeListener = null;
        thread = null;
        stopTime = timer;
        timer = 0;
        isPause = false;
    }
}
